package edu.hawaii.ics.pjdb.result_transport;

import java.util.List;

import org.apache.thrift.TException;
import org.apache.thrift.server.TServer;

import edu.hawaii.ics.pjdb.types.Tuple;
import edu.hawaii.ics.pjdb.types.TupleService.Iface;

public class TupleReceiver implements Iface {
    private final TupleListener listener;
    private TServer server = null;

    public TupleReceiver(TupleListener listener) {
        this.listener = listener;
    }

    @Override
    public void submitTuples(List<Tuple> tuples) throws TException {
        listener.receiveTuples(tuples);
    }

    @Override
    public void finished() throws TException {
        listener.finished();

        if (server == null) {
            throw new IllegalStateException(
                    "TServer in TupleReceiver is unset.");
        }
        server.stop();
    }

    /**
     * In order for this handler to be able to shut down the server after
     * {@link #finished()} is called, it must have a reference to the
     * {@link TServer} it is responsible for. This should be set by whatever
     * code is creating the server.
     * 
     * @param server
     */
    public void setServer(TServer server) {
        this.server = server;
    }
}
